package com.yangrui.app.service.impl;

import com.yangrui.app.entity.Video;
import com.yangrui.app.entity.VideoBanner;
import com.yangrui.app.entity.eVideo;
import com.yangrui.app.service.VideoBannerService;
import com.yangrui.app.service.VideoService;
import com.yangrui.app.service.esService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

@Service
@Slf4j
public class esServiceImpl implements esService {

    @Autowired
    private ElasticsearchRestTemplate template;

    @Autowired
    private VideoService videoService;


    @Override
    public void saveAll() {
        for (Video video : videoService.list()) {
            eVideo res = template.save(new eVideo(video));
            log.info("结果"+res);
        }
    }

    @Override
    public List<eVideo> search(String s) {
        QueryBuilder title = QueryBuilders.matchPhraseQuery("title", s);

        // 构建本地搜索器
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(title)
                .build();

        // 查询数量
        long count = template.count(searchQuery, eVideo.class);
        log.info("检索到一共 {} 个符和条件的文档数据", count);

        Stream<SearchHit<eVideo>> res = template.search(searchQuery, eVideo.class).get();
        List<eVideo> evideos = new ArrayList<>();
        res.forEach(eVideoSearchHit -> eVideoSearchHit.getSortValues());
        return evideos;
    }
}
